

(add-to-load-path "/home/ton/guixsd/modules/")
(setenv "GUIX_PACKAGE_PATH" "/home/ton/guixsd/modules/:$GUIX_PACKAGE_PATH")
(use-modules
 (gnu)
 (gnu system)
 (gnu system nss)
 (gnu packages libusb)
 (gnu packages cups)
 (gnu packages guile-xyz)
 (guix monads)
 (guix store)
 (ice-9 rdelim)
 (srfi srfi-1)
 (nongnu packages linux)
; (ton-nonfree)
; (ton-brother-filter)
 )

(use-service-modules
 desktop base xorg sddm ssh avahi dbus networking cups mcron virtualization
 web pm nfs dns admin docker sound linux)

(use-package-modules
 avahi xorg certs wm code wget admin emacs tmux guile
 ssh linux disk file gnuzilla version-control maths guile crypto gnupg
 password-utils rsync suckless gnome video xdisorg
 terminals ssh image-viewers web-browsers pulseaudio
 tor readline adns fontutils gnunet package-management
 networking lisp cryptsetup fonts python entr gtk nss
 bittorrent engineering graphviz shells compression
 gnome enlightenment dns ghostscript kde-frameworks bash backup nfs
 emacs-xyz printers)

(define quercus-ip "192.168.10.42")

(define (backup-home user)
  #~(let ((borg (string-append #$borg "/bin/borg"))
          (home (format #f "/home/~a" #$user)))
      (system*
       borg "--verbose" "-p"
       "create"
       "--exclude-caches"
       "--exclude" (format #f "~a/.cache/*" home)
       "--one-file-system"
       "--stats" "--list"
       "/mnt/borg::{hostname}-{utcnow}"
       home)
      (system*
       borg "--verbose" "-p"
       "prune"
       "--list"
       "--prefix" "{hostname}-"
       "---within=1w"
       "--keep-daily=7"
       "--keep-weekly=4"
       "--keep-monthly=6"
       "/mnt/borg")))

;; test like
;; ,use (guix monad-repl)
;; ,enter-store-monad
;; (gexp->script "test" (backup-home "alex"))
;; ;; and note what the derivation produces. That's the script to run.
;; (mlet %store-monad ((script (gexp->script "test" (backup-home "alex"))))
;;       (built-derivations (list script)))
;; then, run the script to do a manual backup.

(define backup-home-job
  #~(job '(next-hour '(18))
         #$(backup-home "ton")
         #:user "ton"))

;; Hei her er en forandring

(define battery-check-job
  #~(job '(next-minute (range 0 60 5))
         (lambda ()
           (use-modules ((i3-battery-warning) #:prefix i3-battery-warning:))
           i3-battery-warning:check&react)
         #:user "ton"))

(define updatedb-job
  ;; Run 'updatedb' at 3AM every day.  Here we write the
  ;; job's action as a Scheme procedure.
  #~(job '(next-hour '(3))
         (lambda ()
           (execl (string-append #$findutils "/bin/updatedb")
                  "updatedb"
                  "--prunepaths=/tmp /var/tmp /gnu/store"))
         "Updatedb!"))

;(define tor-socket-check-job
  ;;  Ensure that /var/run/tor/ exists and is owned by tor.
;  #~(job '(next-hour)
;         (lambda () ;; unless(not test)/when(test)?
;           (unless (file-exists? "/var/run/tor")
;             (mkdir "/var/run/tor" #o770)
;             (chown "/var/run/tor" "tor" "tor")))))
;; Check? WTF!? Switch to python? or BASH? or wat? dis is silly.

(define-public %ton-cronjobs (list updatedb-job
                                   battery-check-job
                                   ;;backup-home-job ;; <- causes system build to fail...
                                   ))


;(define hp-laptop-monitor-settings
 ; (call-with-input-file "/home/ton/guixsd/dotfiles/etc/X11/xorg.conf.d/90-monitor.conf" read-string))

;(define mbp-trackpad-settings
;  (call-with-input-file "/home/ton/guixsd/dotfiles/etc/X11/xorg.conf.d/60-mtrack.conf" read-string))

(define %powertop-service
  (simple-service 'powertop activation-service-type
		  #~(zero? (system* #$(file-append powertop "/sbin/powertop")
				    "--auto-tune"))))

(define (remove-services types services)
  (remove (lambda (service)
            (any (lambda (type)
                   (eq? (service-kind service) type))
                 types))
          services))

(define ton-desktop-services
  (remove-services (list upower-service-type );gdm-service-type)
                   %desktop-services))
;  (remove (lambda (service)
;            (eq? (service-kind service) network-manager-service-type upower-service-type))
;          %desktop-services))

;;network-manager-service-type

(operating-system
  (host-name "merlin.browniehive.net")
  (timezone "Europe/Oslo")
  (locale "en_US.utf8")

  (kernel linux-libre-4.4)
  ;;(firmware (cons* ath9k-htc-firmware %base-firmware))
  ;;(kernel linux)
  ;;(firmware (cons* atheros-firmware iwlwifi-firmware %base-firmware))

  (bootloader (bootloader-configuration
                (bootloader grub-efi-bootloader)
                (target "/boot/efi")))

  (kernel-arguments '("syscall.x32=y"
                      "acpi_backlight=vendor"))

  (swap-devices '("/swapfile"))
  (file-systems (cons* (file-system
                         (device (file-system-label "root"))
                         (mount-point "/")
                         (type "ext4"))
                       (file-system
                         (device (file-system-label "BOOT"))
                         (mount-point "/boot/efi")
                         (type "vfat"))
                       (file-system
                         (device (string-append quercus-ip ":/"))
                         (mount-point "/home/ton/quercus-home/")
                         (type "nfs")
                         (mount? #f)
                         (create-mount-point? #t))
                       %base-file-systems))

  (issue "Mercury.\n")

  (users (cons*
          (user-account
           (name "ton")
           (comment "El brownie de casa Merlin")
           (group "users")
           (shell #~(string-append #$bash "/bin/bash"))
           (supplementary-groups '("wheel" "netdev" "audio" "video"
                                   "avahi" "tor"
                                   "users" "kvm" "input"
                                   "libvirt" "docker"
                                   "lp" "lpadmin" 
                                   ))
           (home-directory "/home/ton"))
          %base-user-accounts))
  

;;; Maybe use or adapt alezost-guile al/places.scm?
;;; Add visudo check into sudoers-file PROC - patch into GuixSD?
  (sudoers-file (local-file "/home/ton/guixsd/dotfiles/etc/sudoers"))
  (hosts-file (local-file "/home/ton/guixsd/dotfiles/etc/hosts"))

  (setuid-programs (cons*
                    #~(string-append #$wireshark "/bin/dumpcap")
                    %setuid-programs))

  (packages
    (cons*
     sway ;swaybg swaylock i3status ;;swayidle
     ;;desktop environment scrot is "necessary" for i3lock-fancy
    ;;i3-wm i3status i3lock-fancy scrot hicolor-icon-theme

    libvdpau-va-gl

                                        ;useful tools
;    avahi zip unzip tree mosh mcron
    tmux htop
    the-silver-searcher psmisc wget file strace
    wgetpaste
;    inotify-tools entr
;    rsync dmenu openssh lsh feh stow mcelog wcalc graphviz xdotool
    readline libcap
    sudo glibc-locales
;    gvfs ; for automounting as user

                                        ; fstools
;    dosfstools nfs-utils    

                                        ; X
    ;;xbindkeys xterm  xmodmap setxkbmap xclip xkill
 ;   light brightnessctl
    ;;mako ;; TODO:Necessary?
    xev ;;xdpyinfo xrdb xrandr xfontsel
    pango fontconfig
    font-gnu-unifont font-hack
;    gs-fonts font-wqy-zenhei font-wqy-microhei font-adobe-source-han-sans font-inconsolata

                                        ; audio
;    pulseaudio; pulsemixer

                                        ; laptop specific
    acpi cpupower ;;(TODO:cpupower... wat?)

                                        ; dev
    gnu-make python-3 binutils
 ;   guile-lib guile-2.2

					; terminals and emulators
;    termite
    bash bash-completion

                                        ; Networking, crypto & security
;    gnupg tor torsocks nmap adns iodine pinentry pinentry-gtk2
;    tomb password-store gnunet nftables

                                        ;for HTTPS access
    nss-certs nss

                                        ; emacs
;    emacs emacs-smart-mode-line emacs-rainbow-delimiters
;    emacs-rainbow-identifiers emacs-ag emacs-flycheck emacs-undo-tree
;    emacs-powerline emacs-magit emacs-danneskjold-theme emacs-linum-relative

    %base-packages))

  (services
   (cons*

;    (service alsa-service-type
;             (alsa-configuration
;              (pulseaudio? #t)))

    (service cups-service-type
             (cups-configuration
              (web-interface? #t)
              (browsing? #t)
              (default-paper-size "A4")
              (extensions
               (list cups-filters brlaser))))
;               (list cups-filters brother-mfc-j5730dw))))

    (service tor-service-type
             (tor-configuration
              (config-file (local-file "/home/ton/guixsd/dotfiles/etc/tor/torrc"))))

    (service openssh-service-type
             (openssh-configuration
              (port-number 22)
              (password-authentication? #f)))

;    (service etc-service-type
;             (list '("cgroupssss" ,(plain-file "" ""))
;                   ()))

    (service docker-service-type)
    (service libvirt-service-type
             (libvirt-configuration
              (unix-sock-group "libvirt")
              (tls-port "16555")))
    (service virtlog-service-type
             (virtlog-configuration
              (max-size 2)))

    (service mcron-service-type
             (mcron-configuration
              (jobs %ton-cronjobs)))


    (service nginx-service-type
             (nginx-configuration
              (server-blocks
               (list (nginx-server-configuration
                      (server-name '("merlin.local"))
                      (root "/home/ton/www/")
                      (listen '("80"))
                      (locations
                       (list
                        (nginx-location-configuration
                         (uri "/rp-improv/")
                         (body '("root /home/ton/; autoindex on;")))
                        (nginx-location-configuration
                         (uri "/files/")
                         (body '("root /home/ton/www/; autoindex on;")))))
                      (ssl-certificate #f)
                      (ssl-certificate-key #f))))))

    (service nftables-service-type
             (nftables-configuration
              (ruleset (local-file "/home/ton/guixsd/dotfiles/etc/merlin-firewall.conf"))))

    ;; Fix
;    (service dnsmasq-service-type
;             (dnsmasq-configuration
;              (local-service? #t)
;              (no-resolv? #t)
;              (servers '("82.196.9.45"
;                         "51.255.48.78"
;                         "51.15.98.97"))
;              (listen-addresses '("127.0.0.1"))
;              ))

    (extra-special-file "/usr/bin/env"
                        (file-append coreutils "/bin/env"))
    (extra-special-file "/usr/bin/bash"
                        (file-append bash "/bin/bash"))

    ;; Because i3lock-fancy is a wrapper around i3lock, this is correct...
    ;;(screen-locker-service i3lock-color "i3lock")
    (screen-locker-service swaylock "swaylock")

    (service tlp-service-type)

    (service thermald-service-type)

    (service upower-service-type
             (upower-configuration
              (use-percentage-for-policy? #t)
              (percentage-low 25)
              (percentage-critical 10)
              (percentage-action 5)
              ;;(ignore-lid? #:t)
              (watts-up-pro? #:f)
              (poll-batteries? #:t)
              (critical-power-action 'hybrid-sleep)))

    ;(service rottlog-service-type)
    (service tailon-service-type)

    (service earlyoom-service-type)
             ;;(earlyoom-configuration
              ;;(prefer-regexp "")
              ;;(avoid-regexp "")
              ;;(send-notification-command "")))

    %powertop-service

    (service sddm-service-type
             (sddm-configuration
              (display-server "wayland")
              (remember-last-user? #t)))

                                        ;Modify services! Xorg and so on!
    (remove (lambda (service)
              (let ((type (service-kind service)))
                (or (memq type
                          (list
                           gdm-service-type
                           modem-manager-service-type))
                    (eq? 'network-manager-applet
                         (service-type-name type)))))
    (modify-services
     ton-desktop-services

     (elogind-service-type
      config =>
      (elogind-configuration
       (inherit config)
       (handle-lid-switch 'ignore)))

     (network-manager-service-type
      config =>
      (network-manager-configuration
       (inherit config)
       (dns "dnsmasq")))

     (ntp-service-type
      config =>
      (ntp-configuration
       (inherit config)
       (allow-large-adjustment? #t)))

     (guix-service-type config =>
                         (guix-configuration
                          (inherit config)
                          (substitute-urls (cons*
                                            "https://ci.guix.info/"
                                            "https://berlin.guixsd.org"
                                            %default-substitute-urls))
                          (extra-options '("--max-jobs=1" "--cores=1"))))
      ))

    ))             ; end services
  ;; Allow resolution of '.local' host names with mDNS.
  ;;(name-service-switch %mdns-host-lookup-nss)
  (name-service-switch
    (name-service-switch
      (hosts (list %files    ;first, check /etc/hosts

                   ;; If the above did not succeed, try
                   ;; with 'mdns_minimal'.
                   (name-service
                     (name "mdns_minimal")

                     ;; 'mdns_minimal' is authoritative for
                     ;; '.local'.  When it returns "not found",
                     ;; no need to try the next methods.
                     (reaction (lookup-specification
                                (not-found => return))))

                   (name-service
                     (name "gns")
                     (reaction (lookup-specification
                                (not-found => return))))                
                   ;; Then fall back to DNS.
                   (name-service
                     (name "dns"))
                   ;; Finally, try with the "full" 'mdns'.
                   (name-service
                     (name "mdns"))))))
  )
